<template>
  <div class="blog-detail-container">
    <!-- 博客正文，始终显示 -->
    <div class="blog-header">
      <h1>{{ blog.title }}</h1>
      <div class="blog-meta">
        <span class="author">作者ID: {{ blog.createUser }}</span>
        <span class="time">发布于: {{ blog.createTime }}</span>
        <span class="time" v-if="blog.updateTime && blog.updateTime !== blog.createTime">更新于: {{ blog.updateTime }}</span>
        <span class="views"><i class="fas fa-eye"></i> {{ blog.readCount }} 阅读</span>
        <span class="likes"><i class="fas fa-thumbs-up"></i> {{ blog.likeCount }} 点赞</span>
      </div>
      <div class="blog-tags">
        <el-tag v-for="tag in tags" :key="tag" class="tag">{{ tag }}</el-tag>
      </div>
    </div>
    <div class="blog-content">
      <div class="content-wrapper">
        {{ blog.content }}
      </div>
    </div>
    <div class="blog-actions">
      <el-button type="primary" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回列表
      </el-button>
      <el-button @click="toggleLike" :type="blog.likeStatus === 1 ? 'danger' : 'default'">
        <i :class="blog.likeStatus === 1 ? 'fas fa-heart' : 'far fa-heart'"></i>
        {{ blog.likeStatus === 1 ? '已点赞' : '点赞' }}
      </el-button>
    </div>

    <!-- 评论区，分页只影响评论区 -->
    <div class="comment-section">
      <h2>评论区 ({{ blog.commentCount }})</h2>
      <div v-if="comments.length === 0" class="empty-tip">暂无评论</div>
      <div v-else>
        <div v-for="comment in topLevelComments" :key="comment.id" class="comment-item">
          <div class="comment-main-row">
            <img class="comment-avatar" :src="comment.image || '/avatars/default-avatar.jpg'" alt="头像" />
            <div class="comment-main-content">
              <div class="comment-header">
                <span class="comment-username">{{ comment.userName }}</span>
                <!-- 可加等级/标签 <span class="comment-level">LV5</span> -->
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <span class="comment-action-btn" @click="replyTo(comment)">回复</span>
              </div>
            </div>
          </div>
          <!-- 二级评论 -->
          <div class="comment-replies" v-if="childCommentsMap[comment.id]">
            <div v-for="reply in childCommentsMap[comment.id]" :key="reply.id" class="comment-reply-row">
              <img class="comment-avatar" :src="reply.image || '/avatars/default-avatar.jpg'" alt="头像" />
              <div class="comment-main-content">
                <div class="comment-header">
                  <span class="comment-username">{{ reply.userName }}</span>
                  <span class="comment-time">{{ reply.createTime }}</span>
                  <span class="reply-to" v-if="reply.replyUserName">回复 @{{ reply.replyUserName }}</span>
                </div>
                <div class="comment-content">{{ reply.content }}</div>
                <div class="comment-actions">
                  <span class="comment-action-btn" @click="replyTo(reply)">回复</span>
                </div>
              </div>
              <div v-if="replyingTo && replyingTo.id === reply.id" class="reply-box-fancy">
                <img class="reply-avatar" src="/avatars/default-avatar.jpg" alt="头像" />
                <div class="reply-content-area">
                  <div class="reply-at">
                    回复 <span class="reply-at-username">@{{ replyingTo.userName }}</span>：
                  </div>
                  <el-input
                    v-model="replyContent"
                    type="textarea"
                    placeholder="请输入回复内容..."
                    rows="3"
                    class="reply-input"
                  />
                  <div class="reply-actions">
                    <el-button type="primary" @click="submitReply" class="reply-btn">发布</el-button>
                    <el-button @click="cancelReply" type="text">取消</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="replyingTo && replyingTo.id === comment.id" class="reply-box-fancy">
            <img class="reply-avatar" src="/avatars/default-avatar.jpg" alt="头像" />
            <div class="reply-content-area">
              <div class="reply-at">
                回复 <span class="reply-at-username">@{{ replyingTo.userName }}</span>：
              </div>
              <el-input
                v-model="replyContent"
                type="textarea"
                placeholder="请输入回复内容..."
                rows="3"
                class="reply-input"
              />
              <div class="reply-actions">
                <el-button type="primary" @click="submitReply" class="reply-btn">发布</el-button>
                <el-button @click="cancelReply" type="text">取消</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination" style="margin-top: 1rem; display: flex; align-items: center; gap: 1rem;">
          <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :current-page="commentsPage"
            :page-size="commentsPageSize"
            :total="commentsTotal"
            :page-sizes="[5, 10, 20]"
            @current-change="handleCommentsPageChange"
            @size-change="handleCommentsSizeChange"
            small
          />
        </div>
      </div>
      <!-- 发表评论 -->
      <div class="add-comment">
        <el-input
          v-model="newComment"
          type="textarea"
          placeholder="写下你的评论..."
          rows="3"
        />
        <el-button type="primary" @click="submitComment">发表评论</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const blog = ref<any>({})
const tags = ref<string[]>([])
const comments = ref<any[]>([])
const newComment = ref('')
const replyContent = ref('')
const replyingTo = ref<any>(null)
const commentsPage = ref(1)
const commentsPageSize = ref(5)
const commentsTotal = ref(0)

const topLevelComments = computed(() => comments.value.filter(c => c.parentId === 0))
const childCommentsMap = computed(() => {
  const map: Record<number, any[]> = {}
  comments.value.forEach(c => {
    if (c.parentId !== 0) {
      // 找到它的祖先一级评论id
      let parent = comments.value.find((item: any) => item.id === c.parentId)
      while (parent && parent.parentId !== 0) {
        parent = comments.value.find((item: any) => item.id === parent.parentId)
      }
      const topId = parent ? parent.id : c.parentId
      if (!map[topId]) map[topId] = []
      map[topId].push(c)
    }
  })
  return map
})

const fetchBlogDetail = async () => {
  try {
    const id = route.params.id
    const response = await request.get(`/user/blog/browse/${id}`)
    blog.value = response.data
    // 处理标签
    if (blog.value.tags) {
      tags.value = blog.value.tags.split(',').map((tag: string) => tag.trim())
    }
  } catch (error) {
    console.error('获取博客详情失败:', error)
    ElMessage.error('获取博客详情失败')
  }
}

const fetchComments = async () => {
  try {
    const blogId = route.params.id
    const params = {
      blogId: blogId,
      page: commentsPage.value,
      pageSize: commentsPageSize.value
    }
    const res = await request.get('/user/comment/page', { params })
    comments.value = res.data.records
    commentsTotal.value = res.data.total
  } catch (e) {
    ElMessage.error('获取评论失败')
  }
}

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  await request.post('/user/comment', {
    blogId: route.params.id,
    content: newComment.value,
    parentId: 0,
    replyUserId: null,
    replyCommentId: null,
    level: 1
  })
  newComment.value = ''
  fetchComments()
  fetchBlogDetail()
}

const replyTo = (comment: any) => {
  replyingTo.value = comment
  replyContent.value = ''
}
const cancelReply = () => {
  replyingTo.value = null
  replyContent.value = ''
}
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }
  let parentId = replyingTo.value.parentId === 0 ? replyingTo.value.id : replyingTo.value.parentId
  let replyUserId = replyingTo.value.userId
  let replyCommentId = replyingTo.value.id
  await request.post('/user/comment', {
    blogId: Number(route.params.id),
    content: replyContent.value,
    parentId: parentId,
    replyUserId: replyUserId,
    replyCommentId: replyCommentId,
    replyUserName: replyingTo.value.userName,
    level: 2
  })
  cancelReply()
  fetchComments()
  fetchBlogDetail()
}

const goBack = () => {
  router.back()
}

const handleCommentsPageChange = (page: number) => {
  commentsPage.value = page
  fetchComments()
}
const handleCommentsSizeChange = (size: number) => {
  commentsPageSize.value = size
  commentsPage.value = 1
  fetchComments()
}

const toggleLike = async () => {
  const blogId = Number(route.params.id);
  const isLiked = blog.value.likeStatus === 1;
  const endpoint = isLiked ? '/user/blog/likedelete' : '/user/blog/like';
  const successMessage = isLiked ? '取消点赞成功' : '点赞成功';

  try {
    await request.put(endpoint, { id: blogId });
    blog.value.likeStatus = isLiked ? 0 : 1;
    blog.value.likeCount += isLiked ? -1 : 1;
    ElMessage.success(successMessage);
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
}

onMounted(() => {
  fetchBlogDetail()
  fetchComments()
})
</script>

<style scoped>
.blog-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.blog-header {
  margin-bottom: 2rem;
}

.blog-header h1 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 1rem;
}

.blog-meta {
  display: flex;
  gap: 1.5rem;
  color: #666;
  margin-bottom: 1rem;
}

.blog-meta i {
  margin-right: 0.5rem;
}

.blog-tags {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.tag {
  background-color: #f0f9f4;
  color: #42b983;
  border: none;
}

.blog-content {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 2rem;
}

.content-wrapper {
  line-height: 1.8;
  color: #2c3e50;
  white-space: pre-wrap;
}

.blog-actions {
  display: flex;
  justify-content: flex-start;
  gap: 1rem;
}

.blog-actions .el-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.comment-section {
  background: #fff;
  border-radius: 8px;
  padding: 1.5rem;
  margin-top: 2rem;
}
.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 1rem 0 0.5rem 0;
}
.comment-main-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  background: #f5f5f5;
}
.comment-main-content {
  flex: 1;
}
.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  margin-bottom: 2px;
}
.comment-username {
  color: #e94335;
  font-weight: 600;
}
.comment-level {
  background: #ffe0b2;
  color: #ff9800;
  border-radius: 3px;
  font-size: 12px;
  padding: 0 4px;
}
.comment-time {
  color: #999;
  font-size: 13px;
  margin-left: 8px;
}
.comment-content {
  font-size: 15px;
  color: #222;
  margin: 4px 0 2px 0;
  word-break: break-all;
}
.comment-actions {
  display: flex;
  gap: 12px;
  font-size: 13px;
  color: #888;
}
.comment-action-btn {
  cursor: pointer;
  color: #888;
  transition: color 0.2s;
}
.comment-action-btn:hover {
  color: #1976d2;
}
.comment-replies {
  margin-left: 48px;
  margin-top: 2px;
}
.comment-reply-row {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-top: 8px;
}
.reply-to {
  color: #1976d2;
  font-size: 13px;
  margin-left: 6px;
}
.add-comment, .reply-box { margin-top: 1rem; }
.empty-tip { color: #999; text-align: center; }

.reply-box-fancy {
  display: flex;
  align-items: flex-start;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  padding: 18px 20px 16px 16px;
  margin-top: 1.5rem;
  border: 1px solid #f0f0f0;
  width: 100%;
}
.reply-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 14px;
  margin-top: 2px;
}
.reply-content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.reply-at {
  font-size: 15px;
  color: #888;
  margin-bottom: 6px;
}
.reply-at-username {
  color: #1976d2;
  font-weight: 600;
}
.reply-input {
  width: 100%;
  margin-bottom: 10px;
}
.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.reply-btn {
  min-width: 70px;
}
</style> 